/* eslint-disable react/jsx-max-props-per-line,null,null,null */
/**
 * @Description: 赠品/礼品管理
 * @author ourslookAdmin
 * @date 2019-05-08 14:53:20
 */
import React, {Fragment} from 'react';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Divider,
  Form,
  Icon,
  Input,
  Radio,
  Select,
  Spin,
  Switch,
  Table,
  Tooltip,
} from 'antd';
import {formatMessage, FormattedMessage} from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import {connect} from 'dva';
import {requestLists, requestPromise} from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import {getWebPath} from '../../../utils/request';
import uiUtils, {hasPermission} from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import Ellipsis from '../../../components/ourslook/Ellipsis';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @coming({title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2})
@connect(() => ({}))
class Gift extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: {span: 5},
    wrapperCol: {span: 19},
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {title: 'id', dataIndex: 'id', width: 120, align: 'center', sorter: false, key: 'id'},
    {
      title: '赠品名称',
      dataIndex: 'giftName',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'gift_name',
      render: (value, record, index) => (
        <Fragment>
          <Ellipsis length={10} tooltip>
            {value}
          </Ellipsis>
          {record.productName === null || record.productName === undefined ? (
            <Tooltip title="原商品已删除，该赠品目前无法正常发放">
              <Icon type="warning"/>
            </Tooltip>
          ) : ''}
        </Fragment>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'product_name',
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    // {title: '规格id', dataIndex: 'specId', width: 120, align: 'center', sorter: false, key: 'spec_id'},
    /*{
      title: '领券有效期',
      dataIndex: 'expirationDate',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'expiration_date'
    },*/
    /*{title: '赠品有效期-开始', dataIndex: 'startTime', width: 120, align: 'center', sorter: false, key: 'start_time'},
    {title: '赠品有效期-结束', dataIndex: 'endTime', width: 120, align: 'center', sorter: false, key: 'end_time'},
    {title: '每人限领次数', dataIndex: 'giftLimit', width: 120, align: 'center', sorter: false, key: 'gift_limit'},*/
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      sorter: false,
      key: 'status',
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="可用"
              unCheckedChildren="失效"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 190,
      align: 'center',
      sorter: true,
      key: 'create_time',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 190,
      align: 'center',
      sorter: true,
      key: 'update_time',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>}>
              <Icon type="edit"/>
            </Tooltip>
          </a>
          <Divider type="vertical"/>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>}>
              <Icon type="info"/>
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Gift.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'giftName',
      label: '赠品名称',
      placeholder: '赠品名称',
    },
    {
      type: 'INPUT',
      field: 'productName',
      label: '商品名称',
      placeholder: '商品名称',
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({id: 'ours.curd.list.create'}), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
    this.requestSpecList(selectedRows[0].productId);
  };

  view = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({id: 'ours.curd.show-alert.confirm-delete'}), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotiongift/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionGift = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = promotionGift.id == null ? '/promotiongift/save' : '/promotiongift/update';
        //对象删除一个属性
        //delete promotionGift.xxxxPros;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionGift,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({id: 'ours.curd.show-alert.operate-success'}),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionGift.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {
    //这里处理，发布、取消发布、删除、禁用等状态操作; 参数status由调用放传入
  };

  updateStatus = val => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = -1;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    this.setState({
      loading: true,
    });
    //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotiongift/operatePromotionGiftByIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({id: 'ours.curd.show-alert.operate-success'}),
          'success'
        );
        this.requestList();
      }
    });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========
  requestSpecList = productId => {
    requestPromise(
      `${getWebPath(
        `/mailproductspec/list?productId=${productId === undefined ? '' : productId}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const results = res.page.list;
        const datas = [];
        results.forEach(r => {
          const data = {
            key: r.id,
            name: r.productSpecs,
            value: r.productSpecs,
            price: r.price,
          };
          datas.push(data);
        });
        this.setState({
          specDatas: datas,
        });
      }
    });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotiongift/listVo`, this.params);
  };

  vShow = showListNum => ({display: this.state.showList === showListNum ? 'block' : 'none'});

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{...this.vShow(1)}}
          className={styles.oursCard}
          bodyStyle={{padding: '20px'}}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotiongift:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增"/>
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('promotiongift:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除"/>
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{x: 1200}}
            />
          </div>
        </Card>

        <BackTop/>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
            this.state.showList === 1 ? null : (
              <Card
                title={this.state.editModalTitle}
                bordered={false}
                actions={[
                  <div>
                    <React.Fragment>
                      <Button
                        type="primary"
                        hidden={this.state.editModalType === 'view'}
                        style={{marginRight: '18px'}}
                        onClick={this.saveOrUpdate}
                      >
                        <FormattedMessage id="ours.curd.add.save" defaultMessage="保存"/>
                      </Button>
                      <Button
                        style={{marginRight: '18px'}}
                        onClick={() => {
                          this.editForm.props.form.resetFields();
                          this.setState({showList: 1});
                        }}
                      >
                        <FormattedMessage id="ours.curd.add.back" defaultMessage="返回"/>
                      </Button>
                    </React.Fragment>
                  </div>,
                ]}
                style={{...this.vShow(2)}}
                bodyStyle={{padding: '20px'}}
                ref={node => {
                  this.container = node;
                }}
              >
                <EditForm
                  type={this.state.editModalType}
                  model={this.state.editModel}
                  specModel={this.state.specDatas}
                  wrappedComponentRef={inst => {
                    this.editForm = inst;
                  }}
                />
              </Card>
            )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Gift;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    specModel: PropTypes.array,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    specModel: [],
  };

  constructor(props) {
    super(props);
    this.state = {};
    this.productSearch();
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    /* if (nextProps.model) {
       this.state = {};
       //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
       this.props.model.xxx = 'value';
       this.props.form.setFieldsValue({xxx: 'value'});
     }*/
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const specModel = this.props.specModel || [];
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  productSearch = value => {
    requestPromise(
      `${getWebPath(
        `/mailproduct/listVo?asProduct=0&status=2&productName=${value === undefined ? '' : value}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [];
        datas.forEach(r => {
          results.push(<Option key={r.id}>{r.productName}</Option>);
        });
        this.setState({
          productChildren: results,
        });
      }
    });
  };

  requestSpecList = productId => {
    requestPromise(
      `${getWebPath(
        `/mailproductspec/list?productId=${productId === undefined ? '' : productId}`
      )}`,
      {
        method: 'GET',
      }
      // eslint-disable-next-line consistent-return
    ).then(res => {
      if (res && res.code === 0) {
        const results = res.page.list;
        const datas = [];
        results.forEach(r => {
          const data = {
            key: r.id,
            name: this.specsParse(r.productSpecs),
            value: r.productSpecs,
            price: r.price,
          };
          datas.push(data);
        });
        this.setState({
          specDatas: datas,
        });
        return datas;
      }
    });
  };

  /**
   * 解析规格
   * @param specs
   */
  specsParse = specs => {
    if (specs === null || specs === undefined) {
      return '';
    }
    const productSpecs = JSON.parse(specs);
    let productss = '';
    productSpecs.forEach(s => {
      // eslint-disable-next-line guard-for-in,no-restricted-syntax
      for (const key in s) {
        productss = productss === '' ? s[key] : `${productss},${s[key]}`;
      }
    });
    return productss;
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const specModel = this.props.specModel || [];

    const {
      form,
      form: {getFieldDecorator, getFieldValue, setFieldsValue},
    } = this.props;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 12, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 16}; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };

    const result = [];
    if (type === 'update' || type === 'view') {
      result.push(
        <Option key={model.productId} value={model.productId}>
          {model.productName}
        </Option>
      );
    }

    const rowSelection = {
      hideDefaultSelections: true /*去掉全选和反选*/,
      type: 'radio' /*单选*/,
      onChange: (selectedRowKeys, selectedRows) => {
        //选中了一个
        if (selectedRows.length === 1) {
          this.setState({
            specId: selectedRows[0].key,
          });
          this.props.form.setFieldsValue({specId: selectedRows[0].key});
        }
      },
      /*初始化是选中的向*/
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
        defaultChecked: record.key === model.specId,
      }),
    };

    const specColumns = [
      {
        title: '规格名称',
        dataIndex: 'name',
        key: 'name',
      },
      /*{
        title: '规格值',
        dataIndex: 'value',
        key: 'value',
      },*/
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
      },
    ];

    console.log('this.state:', this.state);
    console.log('model:', model);
    console.log('field:', this.props.form.getFieldsValue());
    // @ts-ignore
    return (
      <Form layout="horizontal" {...formItemLayout}>
        <FormItem label="赠品名称:" {...formItemLayout}>
          {type === 'view'
            ? model.giftName
            : getFieldDecorator('giftName', {
              initialValue: model.giftName,
              rules: [
                {
                  required: true,
                  message: '赠品名称必填',
                },
                {
                  whitespace: true,
                  message: '不能包含空白符',
                },
                {
                  max: 64,
                  message: '最长64个字符',
                },
              ],
            })(
              <Input
                type="text"
                autocomplete="off"
                style={{width: 300}}
                maxlength={64}
                placeholder="赠品名称"
              />
            )}
        </FormItem>
        <FormItem label="商品:" {...formItemLayout}>
          {type === 'view'
            ? model.productName
            : getFieldDecorator('productId', {
              initialValue: model.productId,
              rules: [
                {
                  required: true,
                  message: '商品必填',
                },
                // rulesReg('number'),
              ],
            })(
              <Select
                showSearch
                style={{width: 300}}
                placeholder="请选择商品"
                optionFilterProp="children"
                onChange={value => {
                  this.props.form.setFieldsValue({specId: undefined});
                  this.requestSpecList(value);
                }}
                onSearch={this.productSearch}
                notFoundContent={null}
              >
                {result}
                {this.state.productChildren}
              </Select>
            )}
          &nbsp;&nbsp;
          {type !== 'view' && (
            <Tooltip
              placement="right"
              title="这里只显示商品勾选了作为赠品的。可输入商品名称进行搜索"
            >
              <Icon type="question-circle"/>
            </Tooltip>
          )}
        </FormItem>
        <FormItem label="规格和售价:" style={{marginLeft: 5}} {...formItemLayout}>
          {type === 'view' ? (
            <Fragment>
              {model.productSpecs !== null && model.productSpecs !== undefined
                ? `规格:${model.productSpecs},`
                : ''}
              售价：{model.price}
            </Fragment>
          ) : (
            getFieldDecorator('specId', {
              initialValue: model.specId,
              rules: [
                {
                  required: true,
                  message: '规格必选',
                },
              ],
            })(
              <Table
                rowSelection={rowSelection}
                columns={specColumns}
                dataSource={
                  this.state.specDatas === undefined && type !== 'add'
                    ? this.requestSpecList(model.productId)
                    : this.state.specDatas
                }
                style={{width: 500}}
              />
            )
          )}
        </FormItem>
        {/* <FormItem label="状态:" style={{ marginLeft: 5 }} {...formItemLayout}>
          {type === 'view'
            ? model.status === 1
              ? '可用'
              : '失效'
            : getFieldDecorator('status', {
                initialValue: model.status === undefined ? 1 : model.status,
                rules: [
                  {
                    required: true,
                    message: '状态必填',
                  },
                ],
              })(
                <Select autocomplete="off" style={{ width: 120 }} placeholder="状态">
                  <option value={1}>可用</option>
                  <option value={-1}>失效</option>
                </Select>
              )}
        </FormItem>*/}
      </Form>
    );
  }
}

// eslint-disable-next-line no-class-assign
EditForm = Form.create({})(EditForm);
